<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <el-form label-width="100px" :model="usepwd" :rules="usepwdRules" ref="topwdRef">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="usepwd.old_pwd" placeholder="请输入原密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="usepwd.new_pwd" placeholder="请输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="重新输入新密码" prop="re_pwd">
        <el-input v-model="usepwd.re_pwd" placeholder="请重新输入新密码" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="topwd">修改密码</el-button>
        <el-button @click="rerst">重置密码</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updpwdAPI } from '@/api/uers.js'
export default {
  name: 'UsePwd',
  data() {
    const tooldpwdfo = (rule, value, cb) => {
      if (value !== this.usepwd.old_pwd) {
        cb()
      } else {
        cb(new Error('与原密码一致'))
      }
    }
    const torepwd = (rule, value, cb) => {
      if (value === this.usepwd.new_pwd) {
        cb()
      } else {
        cb(new Error('两次密码不一致'))
      }
    }
    return {
      usepwd: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      usepwdRules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { pattern: /^\S{5,15}$/, message: '非空字符串、长度 6-15', trigger: 'blur' }
        ],
        new_pwd: [
          { pattern: /^\S{5,15}$/, message: '非空字符串、长度 6-15', trigger: 'blur' },
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: tooldpwdfo, trigger: 'blur' }
        ],
        re_pwd: [
          { pattern: /^\S{5,15}$/, message: '非空字符串、长度 6-15', trigger: 'blur' },
          { required: true, message: '请重新输入新密码', trigger: 'blur' },
          { validator: torepwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    topwd() {
      this.$refs.topwdRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await updpwdAPI(this.usepwd)
        if (res.code === 1) {
          this.$message.error(res.message)
        } else {
          this.$message.success(res.message)
          this.$store.dispatch('uers/initUers')
        }
      })
    },
    rerst() {
      this.$refs.topwdRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
